package com.sys.basics.config.aspect;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.sys.basics.config.annotation.SysLogAnnotation;
import com.sys.basics.entity.SysLog;
import com.sys.basics.entity.SysUser;
import com.sys.basics.service.SysLogService;
import com.sys.basics.utils.HttpContextUtils;
import com.sys.basics.utils.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysLogService sysLogService;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation(com.sys.basics.config.annotation.SysLogAnnotation)")
    public void logPointCut() { }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long duration = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, duration);
        return result;
    }

    public void saveSysLog(JoinPoint joinPoint, Long duration) {
        //保存日志
        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //保存用户操作
        SysLogAnnotation curLog = method.getAnnotation(SysLogAnnotation.class);
        if (curLog != null) {
            String value = curLog.value();
            sysLog.setOperation(value);//保存获取的操作
        }

        //保存请求的类名+方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();
        sysLog.setMethod(className + "." + methodName);

        //保存请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JSONUtil.toJsonStr(args);
        sysLog.setParams(params);

        //保存操作者
        SysUser userInfo = ShiroUtils.getUserInfo();
        if(ObjectUtil.isNotNull(userInfo)){
            sysLog.setUserId(userInfo.getId());
            sysLog.setUsername(userInfo.getUsername());
        }

        //保存ip地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        sysLog.setIp(ServletUtil.getClientIP(request));

        //保存时长
        sysLog.setDuration(duration.intValue());

        System.out.println(">>>保存日志到数据库<<<");

        //调用service保存SysLog实体类到数据库
        sysLogService.save(sysLog);
    }
}
